<template>
  <div class="goods-edit-form">
    <form-builder
      ref="form"
      :fields="fields"
      :value="value"
      :is-edit="isEdit"
      mode="goods"
      @update="update"
    >
      <!-- 商品类型 -->
      <template slot="originType" slot-scope="{ field }">
        <form-item :label="field.displayName" class="goods-type">
          {{ name }}
        </form-item>
      </template>

      <!-- 备件/服务项目编号 -->
      <template slot="originCode" slot-scope="{ field }">
        <form-item :label="$t('goods.component.nameNo', {name: codeName})" class="goods-type">
          <el-input :value="value.originCode" :disabled="true"></el-input>
        </form-item>
      </template>

      <!-- 备件/服务项目名称 -->
      <template slot="originName" slot-scope="{ field }">
        <form-item :label="$t('goods.component.name', {name: name})" class="goods-type">
          <el-input :value="value.originName" :disabled="true"></el-input>
        </form-item>
      </template>

      <!-- 类型 -->
      <template slot="originCategory" slot-scope="{ field }">
        <form-item :label="field.displayName" class="goods-type">
          <el-input :value="value.originCategory" :disabled="true"></el-input>
        </form-item>
      </template>

      <!-- 商品图片 -->
      <template slot="attachmentList" slot-scope="{ field }">
        <!-- 对于这种独立的表单项额外增加校验，ref,propField,propValue,validation是必须的 -->
        <form-item
          class="upload-img"
          :class="{
            hide_box:
              value.attachmentList &&
              Object.keys(value.attachmentList).length >= 5,
          }"
          :label="field.displayName"
        >
          <biz-cropper-upload
            action="string"
            list-type="picture-card"
            accept="image/png,image/jpg,image/jpeg"
            :on-preview="handlePictureCardPreview"
            :before-upload="onBeforeUploadImage"
            :http-request="UploadImagePic"
            :file-list="goodsPicList"
            :on-exceed="onExceedPic"
            :on-remove="onRemovePic"
            @cropperDone="picCropperDone"
            multiple
            :limit="5"
            :tips="$t('goods.limit.imgLimit', {num1: '5'})"
            :cropper="{
              autoCropWidth: 750,
              autoCropHeight: 750,
              fixedNumber: [750, 750],
            }"
            formEditingMode="edit"
            @getDeleteFiles="getDeleteFiles"
          ></biz-cropper-upload>
        </form-item>
      </template>

      <!-- 关联产品类型 -->
      <template slot="productTypeList" slot-scope="{ field }">
        <form-item :label="field.displayName">
          <el-cascader
            :placeholder="$t('common.placeholder.selectProductType')"
            popperClass="cascader-checkbox"
            v-model="value.catalogPathIds"
            :options="catalogOption"
            :show-all-levels="false"
            expand-trigger="hover"
            clearable
            :props="catalogCascaderProps"
            filterable
            collapse-tags
            style="width: 100%"
          ></el-cascader>
        </form-item>
      </template>

      <!-- 规格价格区间 -->
      <template
        slot="specsPrice"
        slot-scope="{ field }"
        v-if="isHaveSpecs"
      >
        <form-item :label="field.displayName" class="goods-price">
          <form-text :value="value.specsPrice" :field="field" :disabled="true"></form-text>
        </form-item>
      </template>

      <!-- 价格 -->
      <template
        slot="price"
        slot-scope="{ field }"
        v-if="value.priceType === '2' && !isHaveSpecs"
      >
        <form-item
          :label="field.displayName"
          class="goods-price"
          :validation="validatePrice"
        >
          <el-radio-group :value="value.priceType" @input="updatePriceType">
            <el-radio label="1">{{ $t('goods.component.salesPrice', {name}) }}</el-radio>
            <el-radio label="2">{{$t('goods.component.fillInManually')}}</el-radio>
          </el-radio-group>
          <form-number
            :field="field"
            :value="value.price"
            @update="update"
          ></form-number>
        </form-item>
      </template>
      <!-- 备件/服务项目价格 -->
      <template
        slot="originPrice"
        slot-scope="{ field }"
        v-if="value.priceType === '1' && !isHaveSpecs"
      >
        <form-item :label="$t('goods.component.price')" class="goods-price" :validation="validatePrice">
          <el-radio-group :value="value.priceType" @input="updatePriceType">
            <el-radio label="1">{{ $t('goods.component.salesPrice', {name}) }}</el-radio>
            <el-radio label="2">{{$t('goods.component.fillInManually')}}</el-radio>
          </el-radio-group>
          <form-text :field="field" :value="value.originPrice"></form-text>
          <div class="goods-price-tip">
            {{$t('goods.component.terminalSalesPrice', {data1: name})}}
            <span @click="handleJumpParts">{{$t('goods.component.manage', {data1: name})}}</span>
            {{$t('goods.component.modifyPrice')}}
          </div>
        </form-item>
      </template>

      <!-- 库存 -->
      <template slot="inventoryNumber" slot-scope="{ field }">
        <form-item :label="field.displayName" :validation="validateInventory">
          <el-input v-if="isHaveSpecs" :value="value.inventoryNumber" :disabled="true"></el-input>
          <form-number
            v-else
            :field="field"
            :value="value.inventoryNumber"
            @update="update"
          />
        </form-item>
      </template>

      <!-- 运费 -->
      <template
        slot="expressCost"
        slot-scope="{ field }"
        v-if="
          Array.isArray(value.serviceType) &&
          value.serviceType.includes('快递发货')
        "
      >
        <form-item :label="field.displayName" :validation="validateExpressCost">
          <form-number
            :field="field"
            :value="value.expressCost"
            @update="update"
          />
        </form-item>
      </template>

      <!-- 上门服务费 -->
      <template
        slot="serviceCost"
        slot-scope="{ field }"
        v-if="
          value.originType !== 2 &&
          Array.isArray(value.serviceType) &&
          value.serviceType.includes('上门服务')
        "
      >
        <form-item :label="field.displayName">
          <form-number
            :field="field"
            :value="value.serviceCost"
            @update="update"
          />
        </form-item>
      </template>
      <!-- 是否支持客户上门预约时间 -->
      <template
        slot="isAppointmentSupported"
        slot-scope="{ field }"
        v-if="
          Array.isArray(value.serviceType) &&
          value.serviceType.includes('上门服务')
        "
      >
        <form-item :label="field.displayName">
          <el-radio-group :value="value.isAppointmentSupported" @input="updateIsSupportAppointmentTime">
            <el-radio :label="1">{{ $t('common.base.yes') }}</el-radio>
            <el-radio :label="0">{{ $t('common.base.no') }}</el-radio>
          </el-radio-group>
        </form-item>
      </template>
    </form-builder>
  </div>
</template>

<script>
import MathUtil from '@src/util/math';
import Uploader from 'packages/BaseUpload/uploader';
import BizCropperUpload from '@src/component/business/BizCropperUpload/BizCropperUpload.vue';
import { cloneData } from '@src/api/ProductV2Api';
import { Cascader } from 'element-ui';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import EventBus from '@src/util/eventBus';
export default {
  components: {
    [Cascader.name]: Cascader,
  },
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Object,
      required: true,
    },
    goodsId: {
      type: String,
      default: '',
    },
    pending: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      catalogOption: [],
      catalogCascaderProps: {
        multiple: true,
        value: 'id',
        label: 'name',
        children: 'tasks',
      },
    };
  },
  computed: {
    codeName() {
      return this.value.originType === 1
        ? this.$t('common.base.sparePart')
        : this.value.originType === 2
        ? this.$t('common.label.serviceItem')
        : this.$t('common.pageTitle.pageItemsDetail');
    },
    name() {
      return this.value.originType === 1
        ? this.$t('common.base.sparePart')
        : this.value.originType === 2
        ? this.$t('common.label.serviceItem')
        : this.$t('common.form.type.material');
    },
    goodsPicList() {
      return this.value?.attachmentList || [];
    },
    isHaveSpecs() {
      return this.value?.standardDesc?.hasSpecs || 0
    }
  },
  created() {
    EventBus.$on('priceChange', this.priceChange)
    EventBus.$on('inventoryChange', this.inventoryChange)
  },
  mounted() {
    this.getCatalogOption();
  },
  methods: {
    priceChange(val) {
      let value = this.value;
      this.$set(value, 'specsPrice', val);
      this.$emit('input', value);
    },
    inventoryChange(val) {
      let value = this.value;
      if(!this.value?.standardDesc?.hasSpecs) {
        val = '0'
      }
      this.$set(value, 'inventoryNumber', val);
      this.$emit('input', value);
    },
    validate() {
      return this.$refs.form
        .validate(false)
        .then(valid => {
          return valid;
        })
        .catch(err => console.error(err));
    },
    // 获取树结构
    async getCatalogOption() {
      try {
        let { code, result, message } = await cloneData();
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogOption = result;
        } else {
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message,
          });
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list) {
      list.forEach(item => {
        if (!item.tasks.length) {
          delete item.tasks;
        } else {
          this.deleteEmpty(item.tasks);
        }
      });
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      let value = this.value;
      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },
    // updateNumber({ field, newValue, oldValue }) {
    //   let val = newValue;
    //   if (newValue < 0.01) val = 0.01;

    //   if (newValue > 99999) val = 99999;

    //   let { fieldName, displayName } = field;
    //   let value = this.value;
    //   this.$set(value, fieldName, val);
    //   this.$emit('input', value);
    // },
    updatePriceType(val) {
      let value = this.value;
      this.$set(value, 'priceType', val);
      this.$emit('input', value);
    },
    updateIsSupportAppointmentTime(val) {
      let value = this.value;
      this.$set(value, 'isAppointmentSupported', val);
      this.$emit('input', value);
    },
    updateServiceType(val) {
      let value = this.value;
      this.$set(value, 'serviceType', val);
      this.$emit('input', value);
    },
    updateCatalogIds(val) {
      let value = this.value;
      this.$set(value, 'catalogPathIds', val);
      this.$emit('input', value);
    },
    validateImages() {
      return new Promise((resolve, reject) => {
        // if (Number(value) <= 0) {
        //   return resolve('请输入正确的数量');
        // }

        // if (Number(value) > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) {
        //   return resolve(PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE);
        // }

        // if (count > 2) {
        //   return resolve('最多只能输入2位小数');
        // }
        resolve(null);
      });
    },
    validatePrice(value, field) {
      // 小数位数
      let count = MathUtil.decimalNumber(value);

      return new Promise((resolve, reject) => {
        if (Number(value) < 0.01 || Number(value) > 99999) {
          return resolve(this.$t('goods.limit.priceRange'));
        }

        if (count > 2) {
          return resolve(this.$t('goods.limit.keepDecimal'));
        }

        resolve(null);
      });
    },
    validateInventory(value, field) {
      console.log(value, 444)
      // 小数位数
      let count = MathUtil.decimalNumber(value);

      return new Promise((resolve, reject) => {
        if (Number(value) < 0 || Number(value) > 99999 || count > 0) {
          return resolve(this.$t('goods.limit.stockRange'));
        }

        resolve(null);
      });
    },
    validateExpressCost(value, field) {
      // 小数位数
      let count = MathUtil.decimalNumber(value);

      return new Promise((resolve, reject) => {
        if (Number(value) < 0 || Number(value) > 99999) {
          return resolve(this.$t('goods.limit.freightRange'));
        }

        if (count > 2) {
          return resolve(this.$t('goods.limit.freightKeepDecimal'));
        }

        resolve(null);
      });
    },
    handlePictureCardPreview(file) {
      this.$previewElementImg(file.url);
      // this.$previewImg(file.url);
    },
    onBeforeUploadImage(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt30M = file.size / 1024 / 1024 < 30;

      if (!isJPG) {
        this.$message.error(this.$t('common.validate.imageType'));
      }
      if (!isLt30M) {
        this.$message.error(this.$t('common.validate.imageLimit', {limit: '30mb'}));
      }

      return isJPG && isLt30M;
    },
    /**
     * @description: 获取上传文件
     * @param {Object} param el-upload 返回的文件格式
     * @param {Boolean} isNeedUpload 是否需要调用上传接口
     * @param {Object} files isNeedUpload 则需要带上files
     * @return {Object} file
     */
    async handleGetFile(param, isNeedUpload = true, files) {
      let file = files;
      if (isNeedUpload) {
        const result = await Uploader.upload(param.file, '/files/upload');
        if (result.status != 0) {
          this.$message({
            message: `${result.message}`,
            duration: 1500,
            type: 'error',
          });
          return null;
        }
        file = result.data;
      }
      return !file
        ? null
        : {
            uid: param.file.uid,
            fileId: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          };
    },
    async UploadImagePic(param) {
      const file = await this.handleGetFile(param);
      if (file) {
        this.$set(this.value, 'attachmentList', [
          ...this.value.attachmentList,
          file,
        ]);
      }
    },
    async picCropperDone(beforeFile, afterFile) {
      const result = await this.handleGetFile(
        { file: beforeFile },
        false,
        afterFile
      );
      if (result) {
        this.$set(this.value, 'attachmentList', [
          ...this.value.attachmentList,
          result,
        ]);
      }
    },
    // 文件超出个数限制时的钩子
    onExceedPic() {
      this.$message.error(this.$t('common.validate.imgUploadLimit', {num: '5'}));
    },
    // 文件列表移除文件时的钩子
    onRemovePic(o, a) {
      this.$set(
        this.value,
        'attachmentList',
        this.value.attachmentList.filter(item => item.uid != o.uid)
      );
    },
    handleJumpParts() {
      if (this.value.originType === 1) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PagePartCategoryList,
        });
      } else if (this.value.originType === 2) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageServicePriceList,
        });
      } else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageItemsList,
        });
      }
    },
    getDeleteFiles(files) {
      this.$emit('addNeedServerDeleFiles', files)
    },
  },
};
</script>

<style lang="scss" scoped>
.goods-edit-form {
  padding-bottom: 20px;

  ::v-deep .form-item-label {
    // width: 120px;
  }

  .goods-type {
    margin-bottom: 13px;
    ::v-deep .form-item-control {
      height: 33px;
      line-height: 33px;
    }
  }

  .goods-price {
    .el-radio-group {
      display: flex;
      margin-bottom: 14px;
    }

    .el-radio {
      width: 160px;
    }

    &-tip {
      font-size: 12px;
      color: #8c8c8c;
      margin-top: 14px;

      span {
        color: $color-primary-light-6;
        cursor: pointer;
      }
    }
  }

  .goods-images {
    display: flex;
    align-items: center;
    margin-top: 9px;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
  }

  .goods-service-type {
    .el-checkbox-group {
      display: flex;
    }

    .el-checkbox {
      width: 100px;
      height: 33px;
      line-height: 33px;
    }
  }
}

::v-deep .el-cascader {
  width: 66.6666667%;
  .el-cascader__search-input {
    margin: 2px 0 2px 12px;
  }
}
</style>
<style lang="scss">
.upload-img {
  .el-upload-list__item {
    transition: none !important;
  }
  margin-bottom: 12px;
  .el-upload-list__item label {
    padding: 0;
  }
  .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    margin-bottom: 6px;
    &:hover {
      border-color: $color-primary;
    }
  }
  .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}

.hide_box .el-upload--picture-card {
  display: none;
}

.cascader-checkbox .el-cascader-node__label {
  max-width: 200px;
}
</style>
